import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { notesService, type Note, type CreateNoteData, type UpdateNoteData, type SearchParams } from '../services/notes'
import { useAuthStore } from './auth'

/**
 * 笔记状态管理Store - API版本
 */
export const useNotesStore = defineStore('notes', () => {
  // 状态
  const notes = ref<Note[]>([])
  const currentNote = ref<Note | null>(null)
  const loading = ref(false)
  const error = ref<string | null>(null)
  const searchQuery = ref('')
  const selectedTags = ref<string[]>([])
  const favoriteOnly = ref(false)
  const sortBy = ref<'createdAt' | 'updatedAt' | 'title'>('updatedAt')
  const sortOrder = ref<'asc' | 'desc'>('desc')
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)
  const totalPages = ref(0)

  // 获取认证状态
  const authStore = useAuthStore()

  // 计算属性
  const filteredNotes = computed(() => {
    let filtered = [...notes.value]

    // 本地搜索过滤
    if (searchQuery.value.trim()) {
      const query = searchQuery.value.toLowerCase()
      filtered = filtered.filter(note => 
        note.title.toLowerCase().includes(query) ||
        note.content.toLowerCase().includes(query)
      )
    }

    // 标签过滤
    if (selectedTags.value.length > 0) {
      filtered = filtered.filter(note => 
        note.tags?.some(tag => selectedTags.value.includes(tag))
      )
    }

    return filtered
  })

  const totalNotes = computed(() => total.value)
  const hasMore = computed(() => currentPage.value < totalPages.value)

  // 兼容旧接口的计算属性
  const tags = computed(() => {
    const tagSet = new Set<string>()
    notes.value.forEach(note => {
      note.tags?.forEach(tag => tagSet.add(tag))
    })
    return Array.from(tagSet)
  })

  // 加载笔记列表
  const loadNotes = async (params: SearchParams = {}) => {
    if (!authStore.isAuthenticated) {
      error.value = '请先登录'
      return
    }

    try {
      loading.value = true
      error.value = null
      
      const searchParams: SearchParams = {
        page: currentPage.value,
        limit: pageSize.value,
        search: searchQuery.value || undefined,
        tags: selectedTags.value.length > 0 ? selectedTags.value : undefined,
        ...params
      }

      const response = await notesService.getNotes(searchParams)
      
      if (response.success && response.data) {
        if (params.page === 1 || !params.page) {
          notes.value = response.data.notes || []
        } else {
          const newNotes = response.data.notes || []
          notes.value = [...notes.value, ...newNotes]
        }
        
        total.value = response.data.pagination.total
        totalPages.value = response.data.pagination.pages
        currentPage.value = response.data.pagination.page
      } else {
        throw new Error(response.message || '加载笔记失败')
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '加载笔记失败'
      console.error('Failed to load notes:', err)
    } finally {
      loading.value = false
    }
  }

  // 获取单个笔记
  const getNoteById = async (id: string): Promise<Note | null> => {
    try {
      const cachedNote = notes.value.find(note => note._id === id)
      if (cachedNote) {
        currentNote.value = cachedNote
        return cachedNote
      }

      loading.value = true
      const response = await notesService.getNoteById(id)
      
      if (response.success && response.data) {
        currentNote.value = response.data.note
        return response.data.note
      } else {
        throw new Error(response.message || '获取笔记失败')
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取笔记失败'
      return null
    } finally {
      loading.value = false
    }
  }

  // 创建笔记
  const createNote = async (params: CreateNoteData): Promise<Note | null> => {
    if (!authStore.isAuthenticated) {
      error.value = '请先登录'
      return null
    }

    try {
      loading.value = true
      error.value = null

      const response = await notesService.createNote(params)
      
      if (response.success && response.data) {
        const newNote = response.data.note
        notes.value.unshift(newNote)
        total.value += 1
        currentNote.value = newNote
        return newNote
      } else {
        throw new Error(response.message || '创建笔记失败')
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '创建笔记失败'
      console.error('Failed to create note:', err)
      return null
    } finally {
      loading.value = false
    }
  }

  // 更新笔记
  const updateNote = async (noteId: string, params: UpdateNoteData): Promise<boolean> => {
    if (!authStore.isAuthenticated) {
      error.value = '请先登录'
      return false
    }

    try {
      loading.value = true
      error.value = null

      const response = await notesService.updateNote(noteId, params)
      
      if (response.success && response.data) {
        const updatedNote = response.data.note
        
        const noteIndex = notes.value.findIndex(note => note._id === noteId)
        if (noteIndex !== -1) {
          notes.value[noteIndex] = updatedNote
        }
        
        if (currentNote.value?._id === noteId) {
          currentNote.value = updatedNote
        }
        
        return true
      } else {
        throw new Error(response.message || '更新笔记失败')
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '更新笔记失败'
      console.error('Failed to update note:', err)
      return false
    } finally {
      loading.value = false
    }
  }

  // 删除笔记
  const deleteNote = async (noteId: string): Promise<boolean> => {
    if (!authStore.isAuthenticated) {
      error.value = '请先登录'
      return false
    }

    try {
      loading.value = true
      error.value = null

      const response = await notesService.deleteNote(noteId)
      
      if (response.success) {
        notes.value = notes.value.filter(note => note._id !== noteId)
        total.value -= 1
        
        if (currentNote.value?._id === noteId) {
          currentNote.value = null
        }
        
        return true
      } else {
        throw new Error(response.message || '删除笔记失败')
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '删除笔记失败'
      console.error('Failed to delete note:', err)
      return false
    } finally {
      loading.value = false
    }
  }

  // 搜索笔记
  const searchNotes = async (query: string) => {
    searchQuery.value = query
    currentPage.value = 1
    await loadNotes({ page: 1, search: query })
  }

  // 清除搜索
  const clearSearch = () => {
    searchQuery.value = ''
    selectedTags.value = []
    favoriteOnly.value = false
    currentPage.value = 1
    loadNotes({ page: 1 })
  }

  // 清除错误
  const clearError = () => {
    error.value = null
  }

  return {
    // 状态
    notes,
    currentNote,
    loading,
    error,
    searchQuery,
    selectedTags,
    favoriteOnly,
    sortBy,
    sortOrder,
    currentPage,
    pageSize,
    total,
    totalPages,

    // 计算属性
    filteredNotes,
    totalNotes,
    hasMore,
    tags,

    // 操作
    loadNotes,
    getNoteById,
    createNote,
    updateNote,
    deleteNote,
    searchNotes,
    clearSearch,
    clearError
  }
})